home *** CD-ROM | disk | FTP | other *** search
/ Java Certification Exam Guide / McGrawwHill-JavaCertificationExamGuide.iso / pc / Web Links and Code / code / chap22 / SingleChat.java < prev   
Encoding:
Java Source  |  1997-04-20  |  6.8 KB  |  249 lines

  1. import java.io.*;
  2. import java.net.*;
  3. import java.awt.*;
  4.  
  5. /**
  6.  * SingleChat -- A chat program between a server and one client.
  7.  *
  8.  * To run as a server, do not supply any command line arguments.
  9.  * SingleChat will start listening on the default port, waiting
  10.  * for a connection:
  11.  *   java SingleChat
  12.  *
  13.  * To run as a client, name the server as the first command line 
  14.  * argument:
  15.  *   java SingleChat bluehorse.com
  16.  * or
  17.  *   java SingleChat local          // to run locally
  18.  */
  19.  
  20. public class SingleChat extends Panel {
  21.     Socket    sock;          
  22.     TextArea  receivedText;
  23.  
  24.     private GridBagConstraints c;
  25.     private GridBagLayout      gridBag;
  26.     private Frame              frame;
  27.     private Label              label;
  28.     private int                port = 5001;    // The default port.
  29.     private TextField          sendText;
  30.     private DataOutputStream   remoteOut;
  31.  
  32.  
  33.     public static void main(String args[]) {
  34.        ExitFrame f = new ExitFrame("Waiting for connection...");
  35.  
  36.        String s = null;
  37.        if (args.length > 0)
  38.           s = args[0];
  39.  
  40.        SingleChat chat = new SingleChat(f);
  41.        f.add("Center", chat);
  42.        f.resize(350, 200);
  43.        f.show();
  44.  
  45.         // Make the connection happen.
  46.         if (s == null)
  47.            chat.server();
  48.         else
  49.            chat.client(s);        
  50.  
  51.     }
  52.    
  53.     public SingleChat(Frame f) {     
  54.         frame = f;
  55.  
  56.         // Build the user interface.
  57.         Insets insets = new Insets(10, 20, 5, 10); // bot, lf, rt, top
  58.         gridBag = new GridBagLayout();
  59.         setLayout(gridBag);
  60.  
  61.         c = new GridBagConstraints();
  62.  
  63.         c.insets = insets;
  64.         c.gridy = 0;
  65.         c.gridx = 0;
  66.  
  67.         label = new Label("Text to send:");
  68.         gridBag.setConstraints(label, c);
  69.         add(label);
  70.  
  71.         c.gridx = 1;
  72.  
  73.         sendText = new TextField(20);
  74.         gridBag.setConstraints(sendText, c);
  75.         add(sendText);
  76.  
  77.         c.gridy = 1;
  78.         c.gridx = 0;
  79.  
  80.         label = new Label("Text received:");
  81.         gridBag.setConstraints(label, c);
  82.         add(label);
  83.  
  84.         c.gridx = 1;
  85.  
  86.         receivedText = new TextArea(3, 20); 
  87.         gridBag.setConstraints(receivedText, c);
  88.         add(receivedText);
  89.     
  90.     }
  91.  
  92.     // As a server, we create a server socket bound to the specified
  93.     // port, wait for a connection, and then spawn a thread to 
  94.     // read data coming in over the network via the socket.
  95.  
  96.     private void server() {
  97.         ServerSocket serverSock = null;
  98.         try {
  99.             InetAddress serverAddr = InetAddress.getByName(null);
  100.  
  101.             displayMsg("Waiting for connection on " +
  102.                       serverAddr.getHostName() +
  103.                       " on port " + port);
  104.  
  105.             // We'll only accept one connection for this server.
  106.             serverSock = new ServerSocket(port, 1);
  107.             sock = serverSock.accept();
  108.  
  109.             displayMsg("Accepted connection from " +
  110.                       sock.getInetAddress().getHostName());
  111.  
  112.             remoteOut = new DataOutputStream(sock.getOutputStream());
  113.             new SingleChatReceive(this).start();
  114.  
  115.         } catch (IOException e) {
  116.             displayMsg(e.getMessage() +
  117.                ": Failed to connect to client.");
  118.  
  119.         } finally {
  120.             // At this point, since we only establish one connection
  121.             // per run, we don't need the ServerSocket anymore.
  122.             if (serverSock != null) {
  123.                try {
  124.                   serverSock.close();
  125.                } catch (IOException x) {
  126.                }
  127.             }
  128.         }
  129.     }
  130.  
  131.     // As a client, we create a socket bound to the specified port,
  132.     // connect to the specified host, and then spawn a thread to 
  133.     // read data coming coming in over the network via the socket.
  134.  
  135.     private void client(String serverName) {
  136.         try {
  137.             if (serverName.equals("local"))
  138.                serverName = null;
  139.  
  140.             InetAddress serverAddr = InetAddress.getByName(serverName);
  141.             sock = new Socket(serverAddr.getHostName(), port, true);           
  142.             remoteOut = new DataOutputStream(sock.getOutputStream());
  143.  
  144.             displayMsg("Connected to server " +
  145.                       serverAddr.getHostName() +
  146.                       " on port " + sock.getPort());
  147.  
  148.             new SingleChatReceive(this).start();
  149.  
  150.         } catch (IOException e) {
  151.             displayMsg(e.getMessage() +
  152.                ": Failed to connect to server.");
  153.         }
  154.     }
  155.  
  156.     // Send data out to the socket we're communicating with when
  157.     // the user hits enter in the text field.
  158.     public boolean action(Event e, Object what) {
  159.  
  160.         if (e.target == sendText) {
  161.  
  162.            try {
  163.  
  164.                // Send it.      
  165.               remoteOut.writeUTF(sendText.getText());
  166.  
  167.                // Clear it.
  168.                sendText.setText("");
  169.            
  170.            } catch (IOException x) {
  171.                displayMsg(x.getMessage() +
  172.                   ": Connection to peer lost.");
  173.            }
  174.  
  175.         }
  176.  
  177.         return super.action(e, what);
  178.     }
  179.  
  180.     void displayMsg(String s) {
  181.        frame.setTitle(s);
  182.     }
  183.  
  184.     protected void finalize() throws Throwable {
  185.         try {
  186.            if (remoteOut != null)
  187.               remoteOut.close();
  188.            if (sock != null)
  189.               sock.close();
  190.         } catch (IOException x) {
  191.         }
  192.         super.finalize();
  193.     }
  194.  
  195. }
  196.  
  197. /** So that we can exit when the user closes the frame. */
  198. class ExitFrame extends Frame {
  199.    ExitFrame(String s) {
  200.       super(s);
  201.    }
  202.  
  203.    public boolean handleEvent(Event e) {
  204.        if (e.id == Event.WINDOW_DESTROY) {
  205.             hide();
  206.             dispose();
  207.             System.exit(0);
  208.        }
  209.        return super.handleEvent(e);
  210.    }
  211. }
  212.  
  213. /*
  214.  * SingleChatReceive takes data sent on a socket and displays it in
  215.  * a text area. This receives it from the network.
  216.  */
  217. class SingleChatReceive extends Thread {
  218.     private SingleChat chat;
  219.     private DataInputStream remoteIn;
  220.     private boolean listening = true;
  221.  
  222.     public SingleChatReceive(SingleChat chat) {
  223.         this.chat = chat;
  224.     }
  225.  
  226.     public synchronized void run() {
  227.         String s;
  228.         try {
  229.             remoteIn = new DataInputStream(chat.sock.getInputStream());
  230.  
  231.             while (listening) {
  232.                 s = remoteIn.readUTF();   
  233.                 chat.receivedText.setText(s);    
  234.             }
  235.  
  236.         } catch (IOException e) {
  237.             chat.displayMsg(e.getMessage() +
  238.                ": Connection to peer lost.");
  239.  
  240.         } finally {
  241.            try {
  242.               if (remoteIn != null) 
  243.                  remoteIn.close();
  244.            } catch (IOException x) {
  245.            }
  246.         }
  247.     }
  248. }
  249.